package com.airnews.ticket.ui.flight;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.airnews.ticket.FlyApplication;
import com.airnews.ticket.R;
import com.airnews.ticket.model.CabinItem;
import com.airnews.ticket.model.FlightInfo;
import com.airnews.ticket.model.FlightRestrict;
import com.airnews.ticket.model.Passenger;
import com.airnews.ticket.model.SearchFlight;
import com.airnews.ticket.net.WebAccessor;
import com.airnews.ticket.ui.BaseActivity;
import com.airnews.ticket.ui.login.Login;
import com.airnews.ticket.util.AddrUtil;
import com.airnews.ticket.util.DateUtil;
import com.airnews.ticket.util.FlyUtil;
import com.airnews.ticket.util.StringUtil;
import com.mobclick.android.MobclickAgent;

public class FlyDetail extends BaseActivity implements
		AdapterView.OnItemClickListener ,OnClickListener{
	public final int NORESULT = 1;
	public final int SEARCH_ERROR=2;
	public final int SUCCESS=3;
	
	public static List<FlightInfo> flist;
	public static FlightInfo flight;
	public static FlightRestrict flightRestrict;
	private FlyUtil flyUtil;
	private SimpleAdapter sa;
	private ListView lv;
	private RelativeLayout mBtnNext;
	private ImageView mBtnBack;
	List<Map<String, String>> data = new ArrayList<Map<String, String>>();
	private Button backBut;
	private ProgressDialog progressDialog = null;
	
	public static SearchFlight searchFlight;
	private String ftype;//单程还是双程
	
	private RelativeLayout flightDetailRestrict;
	private TextView restrict;
	private ImageView restrictArrow;
	private String restrictValue;
	
	private SharedPreferences sp;
	
	private Toast toast;
	
	private boolean isOpenRestrict = true;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.flydetail);
		// 删除窗口背景
        getWindow().setBackgroundDrawable(null);
		activityList.add(this);
		
		ftype = (String)getIntent().getSerializableExtra("ftype");
		
		backBut = (Button) findViewById(R.id.backBut);
		backBut.setOnClickListener(this);
		
		//退改签
		flightDetailRestrict = (RelativeLayout) findViewById(R.id.flight_detail_restrict);
		flightDetailRestrict.setOnClickListener(this);
		restrict = (TextView) findViewById(R.id.restrict);
		restrictArrow = (ImageView) findViewById(R.id.restrictArrow);
		
//		String detailRestrict = ((FlyApplication)getApplication()).getPolicyRule();
//		System.out.println("create detailRestrict = " + detailRestrict);
//		if(detailRestrict != null){
//			restrict.setText(detailRestrict);
//			restrictArrow.setVisibility(View.GONE);
//		}
		
		flyUtil = new FlyUtil(this);
		AddrUtil addrUtil = new AddrUtil(this);
		TextView departureDate = (TextView) findViewById(R.id.departureDate);
		String departureTime=flight.departureTime;
		if(departureTime!=null&&departureTime.length()>=10){
			departureTime = departureTime.substring(0,10);
		}
		departureDate.setText("单程 " + departureTime);
		TextView departureWeek = (TextView) findViewById(R.id.departureWeek);
		departureWeek.setText(DateUtil.getWeek("yyyy-MM-dd", departureTime));
		
		TextView fromCity = (TextView) findViewById(R.id.fromCity);
		fromCity.setText(addrUtil.getCityByCode(flight.departure).getCity());
		TextView toCity = (TextView) findViewById(R.id.toCity);
		toCity.setText(addrUtil.getCityByCode(flight.arrival).getCity());
		
		TextView fromtime = (TextView) findViewById(R.id.fromtime);
		fromtime.setText(StringUtil.getTime(flight.departureTime));
		TextView totime = (TextView) findViewById(R.id.totime);
		totime.setText(StringUtil.getTime(flight.arrivalTime));
		TextView fromaf = (TextView) findViewById(R.id.fromaf);
		fromaf.setText(addrUtil.getCityByCode(flight.departure)
				.getAirName());
		TextView toaf = (TextView) findViewById(R.id.toaf);
		toaf.setText(addrUtil.getCityByCode(flight.arrival).getAirName());
		TextView flightno = (TextView) findViewById(R.id.flightNo);
		flightno.setText( flyUtil.getName(flight.airline)+ " " + flight.flightNo);
		TextView airc = (TextView) findViewById(R.id.airc);
		airc.setText(flight.planeType);
		
		TextView stopNo = (TextView) findViewById(R.id.stopNo);
		String stopNoValue = flight.stopNo == 0 ? "直达" : flight.stopNo + "次";
		stopNo.setText(stopNoValue);
		
		String food = flight.isFood == 0 ? "有" : "无";
		TextView foodText = (TextView) findViewById(R.id.food);
		foodText.setText(food);
		
		System.out.println("flight.stopNo="+flight.stopNo+";flight.isFood="+flight.isFood);
		
		TextView cabinPrice = (TextView) findViewById(R.id.cabinPrice);
		TextView price = (TextView) findViewById(R.id.price);
		TextView fuelTax = (TextView) findViewById(R.id.fuelTax);
		TextView baseCabin = (TextView) findViewById(R.id.baseCabin);
		TextView basePrice = (TextView) findViewById(R.id.basePrice);
		TextView discount = (TextView) findViewById(R.id.discount);
		
//		TextView airc0 = (TextView) findViewById(R.id.airc0);//更改条件
//		TextView others = (TextView) findViewById(R.id.others);//退票条件
//		TextView airc1 = (TextView) findViewById(R.id.airc1);//签转条件
//		TextView airc2 = (TextView) findViewById(R.id.airc2);//备　　注
		
		List<CabinItem> cabinlist = flight.cabinItemsDetails;
		if(cabinlist!=null&&cabinlist.size()>0){
        	CabinItem cabinItem= cabinlist.get(0);//cabinlist.size()-1
        	
			baseCabin.setText(FlyUtil.getJClassName(cabinItem.baseCabin) + " " + cabinItem.baseCabin);
			
			String priceFormat = cabinItem.price.indexOf(".00") != -1 ? cabinItem.price.substring(0, cabinItem.price.indexOf(".00")) : cabinItem.price;
        	String ibePaymentFormat = cabinItem.ibePayment.indexOf(".00") != -1 ? cabinItem.ibePayment.substring(0, cabinItem.ibePayment.indexOf(".00")) : cabinItem.ibePayment;
        	String cabinPriceFormat = cabinItem.cabinPrice.indexOf(".00") != -1 ? cabinItem.cabinPrice.substring(0, cabinItem.cabinPrice.indexOf(".00")) : cabinItem.cabinPrice;
        	Float priceCal = Float.parseFloat(cabinPriceFormat) - Float.parseFloat(priceFormat);
        	
			cabinPrice.setText("￥" +cabinPriceFormat + "元");
			price.setText("￥" + String.valueOf(priceFormat)  + "元");
			discount.setText("(" + FlyUtil.parseDiscount(cabinItem.discount)  + ")");
			discount.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG );
			basePrice.setText("       返利" + priceCal + "元");
			
			
			cabinPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG );
			String airportTaxV = (cabinItem.airportTax.equals("") ||  (cabinItem.airportTax == null) ? "0" : cabinItem.airportTax) ;
			String fuelTaxV = (cabinItem.fuelTax.equals("") || (cabinItem.fuelTax == null) ? "0" : cabinItem.fuelTax);
			fuelTax.setText("￥" + airportTaxV + "/￥" + fuelTaxV );
			float sumPrice = Float.valueOf(cabinItem.price) + Float.valueOf(airportTaxV) + Float.valueOf(fuelTaxV);
        	String sumPriceFormat = String.valueOf(sumPrice).indexOf(".0") != -1 ? String.valueOf(sumPrice).substring(0, String.valueOf(sumPrice).indexOf(".0")) : String.valueOf(sumPrice);
			TextView sumPriceText = (TextView) findViewById(R.id.sumPrice);
			sumPriceText.setText("总支付：" + sumPriceFormat + "元");
			
//			others.setText(flightRestrict.airc0);
			
        }
		
		
		
		
		mBtnNext = (RelativeLayout)findViewById(R.id.btn_next);
		
		mBtnNext.setOnClickListener(this);
	    //new GetWeatherIcon().execute(eDeparture,eArrival);
	}
	
	public void onClick(View v) { 
		switch (v.getId()) {
		case R.id.backBut:
			Intent intent3 = new Intent();
			intent3.setClass(FlyDetail.this, FlyList.class);
			intent3.putExtra("ftype", "single");
			FlyList.searchFlight = searchFlight;
			FlyList.flist = flist;
			startActivity(intent3);
			break;
		case R.id.btn_next:
			sp = getSharedPreferences("UserInfoB2C", Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE);
	        String userIdLogin = sp.getString("userId", null);
	        String isLoninOK = sp.getString("isLoninOK", null);
	        String autoLogin = sp.getString("isAutoLogin", null);
	        System.out.println("isLoninOK=="+isLoninOK);
	        System.out.println("autoLogin=="+autoLogin);
	        if(autoLogin==null && isLoninOK == null){
	        	Intent it = new Intent(FlyDetail.this, Login.class);
	        	Login.flight = flight;
	        	Login.searchFlight = searchFlight;
	        	Login.returnFlight = null;
				startActivity(it);
				overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
	        } else {
				Intent intent = new Intent();
				intent.setClass(FlyDetail.this, FlyOrderInput.class);
				FlyOrderInput.flight = flight;
				FlyOrderInput.searchFlight = searchFlight;
				FlyOrderInput.returnFlight = null;
				FlyOrderInput.isItinerary = "0";
				FlyOrderInput.itineraryList =  new ArrayList<Map<String,String>>();
				startActivity(intent);
	        }
			break;
		case R.id.flight_detail_restrict:
			if(isOpenRestrict){
				String detailRestrict = ((FlyApplication)getApplication()).getPolicyRule();
				if(detailRestrict == null){
					if(restrictValue != null){
						restrict.setText(restrictValue);
						restrictArrow.setVisibility(View.GONE);
					} else {
						getFlightRestrict();
					}
				}
				isOpenRestrict = false;
			} else {
				restrict.setText("点击查看详细...");
				restrictArrow.setVisibility(View.GONE);
				isOpenRestrict = true;
			}
		}
	}

	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Intent intent = new Intent();
		intent.setClass(this, Passenger.class);
//		Passenger.flight = flight;
//		Passenger.cabinItem=flight.cabinItems.get(position);
//		Passenger.data=new ArrayList<Map<String,String>>();
		startActivity(intent);
	}
	
	private void getFlightRestrict() {
		progressDialog = ProgressDialog.show(this, "请稍等...", "查询退改签明细...",true);
		final Thread thread = new Thread() {
			public void run() {
				flightRestrict =  WebAccessor.getFlightRestrict(FlyDetail.this,flight);
				
				if (progressDialog.isShowing()) {
					if (flightRestrict!= null) {
						Message msg = new Message();
						msg.what = SUCCESS;
						myHandler.sendMessage(msg);
					} else {
						Message msg = new Message();
						msg.what = SEARCH_ERROR;
						msg.obj = "无法查询到退改签明细";
						myHandler.sendMessage(msg);
					}
				}
				progressDialog.dismiss();
			}
		};
		progressDialog.setCancelable(true);
		thread.start();
	}
	
	public Handler myHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SEARCH_ERROR:
				toast = Toast.makeText(FlyDetail.this, (String)msg.obj, Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				break;
			case SUCCESS:
				restrictValue = flightRestrict.airc0;
				//退订票规则
//				((FlyApplication)getApplication()).setPolicyRule(restrictValue);
//				System.out.println("restrictValue="+restrictValue);
				restrict.setText(restrictValue);
				restrictArrow.setVisibility(View.GONE);
				break;
			}
		}
	};
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){
			Intent intent3 = new Intent();
			intent3.setClass(FlyDetail.this, FlyList.class);
			intent3.putExtra("ftype", "single");
			FlyList.searchFlight = searchFlight;
			FlyList.flist = flist;
			startActivity(intent3);
			
			return true;
		}
		return super.onKeyDown(keyCode, event);
	} 
	
	public void onResume() {     
		super.onResume();     
		MobclickAgent.onResume(this); 
	}  
	
	public void onPause() {     
		super.onPause();     
		MobclickAgent.onPause(this); 
	}  
}
